package com.imooc.mymall.util;


import com.imooc.mymall.exception.ErrorCodeEnum;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Set;

/**
 * <h1>校验工具类</h1>
 * @Author: crowsjian
 * @Date: 2020/7/12 22:01
 */
public class ValidatorUtils {
    // 校验器
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * <h2>参数校验</h2>
     * @param object
     * @param groups
     * @param <T>
     */
    public static <T> void validate(T object,Class... groups){
        Set<ConstraintViolation<T>> validate = validator.validate(object,groups);
        // 如果校验结果不为空
        if(!CollectionUtils.isEmpty(validate)){
            StringBuilder exceptionMessage = new StringBuilder();
            validate.forEach(constraintViolation->{
                exceptionMessage.append(constraintViolation.getMessage());
            });
            throw new RuntimeException(exceptionMessage.toString());
        }
    }
}
